import { Injectable } from '@angular/core';
import {RequestUtil} from "../../../../util/request-util";
import {FormUtil} from "../../../../util/form-util";
import {DamAPI} from "../../peach-constants";
import {Observable} from "rxjs";
import {MsgResult} from "../../../../models/msg-result";
import {Area,MapPoint} from "./area";

@Injectable()
export class EncircledAreaService {

  constructor(
    private requestUtil:RequestUtil,
    private formUtil : FormUtil
  ) { }


  /**
   * 添加合围区
   * @param account : 对象实例
   * @returns {Observable<MsgResult>|any}
   */
  add(area: Area):Observable<MsgResult>{
    let mapPoints: MapPoint[] = area.mapPoints;

    let orderNums:Array<any>  = [];
    let pointAddresses:Array<any>  = [];
    let lons : Array<any>  = [];
    let lats : Array<any>  = [];
    mapPoints.forEach(function (point : MapPoint) {
      orderNums.push(point.orderNum);
      pointAddresses.push(point.pointAddress);
      lons.push(point.lon);
      lats.push(point.lat);
    });

    let params="areaName="+area.areaName+"&siteCode="+area.siteCode+"&lon="+lons.join(",")+"&lat="+lats.join(",")+"&pointAddress="+pointAddresses.join(",")+"&orderNum="+orderNums.join(",");

    console.log(JSON.stringify(mapPoints));
    return this.requestUtil.post(DamAPI.add,params);
  }

  /**
   * 删除合围区
   * @param id :账户id
   * @returns {Observable<MsgResult>|any}
   */
  deleteArea(id):Observable<MsgResult>{
    return this.requestUtil.delete(DamAPI.delete+"/"+id+"?format=json");
  }

  /**
   * 根据id查询
   * @request :http://localhost:8080/one-admin/api/accounts/123?format=json
   * @param id:账号id；
   * @returns {Observable<MsgResult>|any}
   */
  getAreaById(id):Observable<MsgResult>{
    return this.requestUtil.get(DamAPI.getById+"/"+id+"?format=json");
  }

  /**
   * 修改
   *
   * @param area
   * @returns {Observable<MsgResult>|any}
   */
  editArea(area:Area):Observable<MsgResult>{
    let mapPoints: MapPoint[] = area.mapPoints;
    let orderNums:Array<any>  = [];
    let pointAddresses:Array<any>  = [];
    let lons : Array<any>  = [];
    let lats : Array<any>  = [];
    let pointIds:Array<any>  = [];
    mapPoints.forEach(function (point : MapPoint) {

      pointIds.push(point.pointId);
      orderNums.push(point.orderNum);
      pointAddresses.push(point.pointAddress);
      lons.push(point.lon);
      lats.push(point.lat);
    });

    let params="areaName="+area.areaName+"&siteCode="+area.siteCode+"&lon="+lons.join(",")+"&lat="+lats.join(",")+"&pointAddress="+pointAddresses.join(",")+"&pointId="+pointIds.join(",")+"&orderNum="+orderNums.join(",");
    return this.requestUtil.put(DamAPI.edit+"/"+area.id+"?format=json&"+params);
  }

//批量删除
  deletes(ids : Array<string>):Observable<MsgResult>{
    let params="ids="+ids;
    return this.requestUtil.post(DamAPI.deletes,params);
  }

  //获取合围区站点名称
  findSitesInfos():Observable<MsgResult>{
    return this.requestUtil.post(DamAPI.findSitesInfo);
  }

}
